package com.thunder.rebot.rebotclient.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.RectF;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.app.AlertDialog;
import android.text.Layout;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

//import com.github.chrisbanes.photoview.OnMatrixChangedListener;
//import com.github.chrisbanes.photoview.OnOutsidePhotoTapListener;
//import com.github.chrisbanes.photoview.OnPhotoTapListener;
//import com.github.chrisbanes.photoview.OnScaleChangedListener;
//import com.github.chrisbanes.photoview.OnSingleFlingListener;
//import com.github.chrisbanes.photoview.PhotoView;
import com.google.gson.Gson;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.adapter.PersonAdapter;
import com.thunder.rebot.rebotclient.entity.MapCenterEntity;
import com.thunder.rebot.rebotclient.entity.PersonEntity;
import com.thunder.rebot.rebotclient.entity.ScaleEntity;
import com.thunder.rebot.rebotclient.entity.TaskDots;
//import com.thunder.rebot.rebotclient.iml.ImageViewScaleChangeListenerIml;
import com.thunder.rebot.rebotclient.entity.TestA;
import com.thunder.rebot.rebotclient.entity.TestB;
import com.thunder.rebot.rebotclient.entity.TestC;
import com.thunder.rebot.rebotclient.entity.WifiEnty;
import com.thunder.rebot.rebotclient.entity.Wifilists;
import com.thunder.rebot.rebotclient.iml.OnCustomMatrixChangedListener;
import com.thunder.rebot.rebotclient.iml.OnCustomOutsidePhotoTapListener;
import com.thunder.rebot.rebotclient.iml.OnCustomPhotoTapListener;
import com.thunder.rebot.rebotclient.iml.OnCustomScaleChangedListener;
import com.thunder.rebot.rebotclient.iml.OnCustomSingleFlingListener;
import com.thunder.rebot.rebotclient.iml.OnDragListener;
import com.thunder.rebot.rebotclient.iml.OnMyFling;
import com.thunder.rebot.rebotclient.iml.OnScrollListener;
import com.thunder.rebot.rebotclient.iml.OnTvClickListener;
import com.thunder.rebot.rebotclient.iml.SteerWheelListener;
import com.thunder.rebot.rebotclient.utils.AudioRecordDemo;
import com.thunder.rebot.rebotclient.utils.AudioStream;
import com.thunder.rebot.rebotclient.utils.CommonUtils;
import com.thunder.rebot.rebotclient.utils.MediaRecordDemo;
import com.thunder.rebot.rebotclient.view.CircleView;
import com.thunder.rebot.rebotclient.view.CustomListviewPopwindow;
import com.thunder.rebot.rebotclient.view.CustomPopwindow;
import com.thunder.rebot.rebotclient.view.MyPhontoView;
import com.thunder.rebot.rebotclient.view.ZZoomImageView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TestActivity extends BaseActivity implements View.OnClickListener/*implements GestureDetector.OnGestureListener,
        View.OnClickListener, ScaleGestureDetector.OnScaleGestureListener*/{
    private String TAG = TestActivity.class.getSimpleName();
    //定义手势检测
    GestureDetector detector = null;
    //缩放检测
    ScaleGestureDetector scDetector = null;
    private MyPhontoView zZoomImageView;
    private ArrayList<TaskDots> dots;
    private ArrayList<TextView> textViews;
    private int screenWidth;//屏幕的宽高
    private MapCenterEntity mce;
    private FrameLayout fl;
//    private ImageViewScaleChangeListenerIml imageViewScaleChangeListenerIml;
    private ImageView ivLocation;

//    float initxx;
//    float inityy;




    private Button testGet;
    private Button testScges;
    private Button btSelectPerson;

    private TextView tvWifiList;


//初始化 方向盘
    private CircleView circleView;
    private void initCircleView(){
        circleView = findViewById(R.id.circle_wheel);
        circleView.setOnSteerWheelListener(new SteerWheelListener() {
            @Override
            public void direction(final CircleView.Dir dir) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(TestActivity.this, "@@wp:" + dir,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }



    private void  saveData(String string){
        try { // 防止文件建立或读取失败，用catch捕捉错误并打印，也可以throw

            /* 读入TXT文件 */
//            String pathname = "D:\\twitter\\13_9_6\\dataset\\en\\input.txt"; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径
//            File filename = new File(pathname); // 要读取以上路径的input。txt文件
//            InputStreamReader reader = new InputStreamReader(
//                    new FileInputStream(filename)); // 建立一个输入流对象reader
//            BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
//            String line = "";
//            line = br.readLine();
//            while (line != null) {
//                line = br.readLine(); // 一次读入一行数据
//            }

            /* 写入Txt文件 */  //new OutputStreamWriter(new FileOutputStream(file, true))
            Log.w(TAG,"PATH:" + Environment.getExternalStorageDirectory());
            File writename = new File(Environment.getExternalStorageDirectory()+"/wifiname.txt"); // 相对路径，如果没有则要建立一个新的output。txt文件
            if(!writename.exists()){
                writename.createNewFile(); // 创建新文件
            }
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(writename, true));
            out.write("\n\t*************************");
            out.write(string + "\r\n"); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



private TextView wifis;
//    private AudioStream audioStream ;
//    private MediaRecordDemo mediaRecordDemo;
    private AudioRecordDemo audioRecordDemo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        audioRecordDemo = new AudioRecordDemo();
//        audioStream = new AudioStream();
        wifis = findViewById(R.id.wifis);
        fl =  findViewById(R.id.fl);
        zZoomImageView = (MyPhontoView) findViewById(R.id.phtoview);
        testGet = (Button) findViewById(R.id.bt_test_ges);
        testGet.setOnClickListener(this);
        testScges = (Button) findViewById(R.id.bt_test_scges);
        testScges.setOnClickListener(this);
        btSelectPerson = (Button) findViewById(R.id.btSelectPerson);
        btSelectPerson.setOnClickListener(this);
        initSelectPersonPopwindow(btSelectPerson);
        ivLocation = findViewById(R.id.iv_location);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();

        tvWifiList = findViewById(R.id.tv_wifilist_voce);
        initData();
        addView();


        float aa = ivLocation.getX();
        float bb = ivLocation.getY();
//        Log.w("TAG", "WP1:" + "initxx:" + initxx  + "==" + inityy);
        initListener();

        initCircleView();

        ///


        TestA ta = new  TestA();
        ta.setWifiName("1");
        ta.setLevel("-56");
        TestA ta2 = new  TestA();
        ta2.setWifiName("2");
        ta2.setLevel("-562");
        ArrayList<TestA> lsit = new ArrayList<>();
        lsit.add(ta);
        lsit.add(ta2);
        TestB tb1 = new TestB();
        tb1.setX("1");
        tb1.setY("1");
        tb1.setTemp("20");
        tb1.setWifiCount("2");
        tb1.setNoise("22");
        tb1.setLists(lsit);

        tb1.setLists(lsit);
        ArrayList<TestB> l = new ArrayList<>();
        l.add(tb1);

        TestC tc1 = new TestC();
        tc1.setNodeName("1");
        tc1.setNodeLists(l);


        Gson g = new Gson();
        Log.w(TAG, "@@@@@@@@@@@@@@@@@" +g.toJson(tc1) );
//        audioStream.startRecord();
//        mediaRecordDemo = new MediaRecordDemo();
//        mediaRecordDemo.startRecord();



        task = new TimerTask() {
            @Override
            public void run() {
                saveSensor();
            }
        };

        timer = new Timer();
        timer.schedule(task,100,500);


        audioRecordDemo.getNoiseLevel();
    }
    int i = 0;
    private void saveSensor(){
//        QuerySQLEntity.ResponseQuery responseQuery = null;
//        double noise = -0.1f;
////        if (recorderManager != null) {
////            noise = recorderManager.getNoise();
////        }
        List<ScanResult> wifilists = getWifiList();
//        responseQuery = new QuerySQLEntity.ResponseQuery();
//        responseQuery.type = 12;
//        responseQuery.frame = "1013";


//        responseQuery.voice = noise + "";
        HashMap<String, String> hashMap = new HashMap<>();

        for (ScanResult sr : wifilists) {
            if(sr.SSID.equals("jyw-450M;;")){
//                hashMap.put(i + "", sr.SSID + ":" + sr.level);
                hashMap.put(i + "", "value" + ":" + sr.level);
                ++i;
                if(i > 65536000)i = 0;
            }
//            hashMap.put(i + "", sr.SSID + ":" + sr.level);

        }
        if(hashMap != null){
            Log.w(TAG,"@@@WP wifi:" + hashMap.toString());
//        if()
//        responseQuery.hashMap = hashMap;
//        Log.d(TAG,"sensor robot:" + responseQuery.toString());
//        synchronized (this){
//            if(mPrefs != null){
//                SharedPreferences.Editor edit = mPrefs.edit();
//                edit.putString("sensor",new Gson().toJson(responseQuery));
//                edit.commit();
//            }
//            Log.d(TAG,"read mPrefs:" + getSensor());
        }
    }

    private TimerTask task;
    private Timer timer ;

    private boolean isfirst = true;
    /*icon的初始值*/
    float initxx;
    float inityy;
    float constInitxx;
    float constInityy;
/*默认边框的初始值*/
    float initLocationleft = 0;
    float initLocationtop = 24;

    float initLocationtight = 720;
    float initLocationbottom = 744;

    private float transelateTop = 0;
    private float transelateBottom = 768;


    private int gesture = 0;

    private boolean isReverse = true;//默认是在初始值



    private CustomPopwindow customPopwindow;



//    /**
//     * 获取wifi列表
//     */
//    private WifiManager wifiManager;
//    private List<ScanResult> listb=null;
//    private List<ScanResult> getWifiList(){
//        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        wifiManager.startScan();
//        listb = wifiManager.getScanResults();
//        if(listb != null) {
//            WifiInfo wi = wifiManager.getConnectionInfo();
//            Log.w(TAG, "listb:" + listb.toString() + "'''" + wi.getBSSID());
//        }
//        return listb;
//    }


    private void initListener() {
        initxx = 0;//ivLocation.getX();
        inityy = 0;//ivLocation.getY();
//        constInitxx = ivLocation.getX();
//        constInityy = ivLocation.getY();
//        zZoomImageView.setScaleType(ImageView.ScaleType.MATRIX);
        /*缩放*/
        zZoomImageView.setOnScaleChangeListener(new OnCustomScaleChangedListener() {
            @Override
            public void onScaleChange(float scaleFactor, float focusX, float focusY) {
                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; focusX:" + focusX + "; focusY:" + focusY);
                if(isfirst){
//                    initxx = textViews.get(0).getX();
//                    inityy = textViews.get(0).getY();
//                    initxx = ivLocation.getX();
//                    inityy = ivLocation.getY();
                    //initxx = 0;//ivLocation.getX();
                    //inityy = 0;//ivLocation.getY();
                    constInitxx = ivLocation.getX();
                    constInityy = ivLocation.getY();
                    isfirst = false;
//                    Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxx:" + location[0] + "; inityy:" + location[1]);
                }


//                int[] location = new int[2];
//                textViews.get(0).getLocationOnScreen(location);
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxx:" + location[0] + "; inityy:" + location[1]);

//                Layout layout = textViews.get(0).getLayout();
//                layout.getTopPadding();
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxx:" + layout.getTopPadding() + "; inityy:" + inityy);

//                float initx = screenWidth/2 + new Double(1.0 /0.05 * (screenWidth /384)).intValue() - 50;
//                float inity = new Double(mce.getyPix()/2).intValue() - new Double(1.0/0.05 * (mce.getyPix() /384)).intValue() - 40;
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initx:" + initx + "; inity:" + inity);

//                Log.w(TAG,"@@wp scale after:" + scaleFactor + "; aX:" + (focusX + Math.abs(initxx - focusX) * scaleFactor) + "; aY:" + (focusY + Math.abs(initxx - focusY)*scaleFactor));
                ScaleEntity scaleEntity = new ScaleEntity();
                scaleEntity.setScale(scaleFactor);
                //scaleEntity.setAx((focusX + Math.abs(initxx - focusX) * scaleFactor));
                //scaleEntity.setAy((focusY + Math.abs(inityy - focusY)*scaleFactor));
                //scaleEntity.setAx(initxx * scaleFactor - focusX * (1 - 1/scaleFactor) - initxx);
                //scaleEntity.setAy(inityy * scaleFactor - focusY * (1 - 1/scaleFactor) - inityy);
                scaleEntity.setAx(initxx * scaleFactor - (focusX - constInitxx) * (1 - 1/scaleFactor));
                scaleEntity.setAy(inityy * scaleFactor - (focusY - constInityy) * (1 - 1/scaleFactor));
//                scaleEntity.setAx(initxx-1);
//                scaleEntity.setAy(inityy-1);
                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxxe:" + (initxx )+ "; inityye:" + inityy );

                Message msg = handler.obtainMessage();
                msg.arg1 = 10;
                msg.obj = scaleEntity;
                handler.sendMessage(msg);

            }
        });
        /**在原图片上面，进行滑动，显示距离*/
        zZoomImageView.setOnSingleFlingListener(new OnCustomSingleFlingListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.w(TAG,"@@wp onFling velocityX:" + velocityX + "; velocityY:" + velocityY  + "scale:"+zZoomImageView.getScale() +"--" +e1.getX() + "--" + "--"+e1.getRawX() +"--" +e1.getY() + "--" + "--"+e1.getRawY() + "--" +e2.getX() + "--" + "--"+e2.getRawX()+ "--" +e2.getY() + "--" + "--"+e2.getRawY());
                return false;
            }
        });
        /**单击屏幕，选择图片中的点 范围x0-1，同理y*/
        zZoomImageView.setOnPhotoTapListener(new OnCustomPhotoTapListener() {
            @Override
            public void onPhotoTap(ImageView view, float x, float y) {
                Log.w(TAG,"@@wp onPhotoTap x:" + x + "; y:" + y );
            }
        });
        zZoomImageView.setOnOutsidePhotoTapListener(new OnCustomOutsidePhotoTapListener() {
            @Override
            public void onOutsidePhotoTap(ImageView imageView) {

            }
        });
        zZoomImageView.setOnFlingListener(new OnMyFling() {
            @Override
            public void onFling(float startX, float startY, float velocityX, float velocityY) {
                Log.w(TAG, "@@@wp:startX:" + startX + " startY:" + startY + " velocityX:" + velocityX + " velocityY:" + velocityY);
            }
        });
        zZoomImageView.setOnMatrixChangeListener(new OnCustomMatrixChangedListener() {
            @Override
            public void onMatrixChanged(RectF rect) {
                Log.w(TAG, "@@@ left:" + rect.left + "top:" + rect.top +"right:" + rect.right + "bootom:" + rect.bottom + "top:" + transelateTop+"transelateBottom:" + transelateBottom);
                if(initLocationleft == rect.left && initLocationtop == rect.top && initLocationtight == rect.right && initLocationbottom == rect.bottom ){
                    isReverse = true;
                }else{
                    isReverse = false;
                    if (initLocationleft == rect.left ) {//到左边 或者右边  x的值都不变化
                        //到top 或者是 bottom
                        if (transelateTop == rect.top ||transelateBottom == rect.bottom) {//  x 的值都是不变化
                            gesture = 2;
                        }else{
                            gesture = 1;
                        }

                    }else if (transelateTop == rect.top ){  //到上边或者底部   y的值不变化
                        //到left 或者是 bootom
                        if (initLocationleft == rect.left ||initLocationtight == rect.right) {//   y的值都是不变化
                            gesture = 4;
                        }else{
                            gesture = 3;
                        }
                    }else if(initLocationtight == rect.right){
                        //到left 或者是 bootom
                        if (transelateTop == rect.top ||transelateBottom == rect.bottom) {//   y的值都是不变化
                            gesture = 6;
                        }else{
                            gesture = 5;
                        }
                    }else if (transelateBottom == rect.bottom){
                        //到left 或者是 bootom
                        if (initLocationleft == rect.left ||initLocationtight == rect.right) {//   y的值都是不变化
                            gesture = 8;
                        }else{
                            gesture = 7;
                        }
                    }else{
                        gesture = 9;
                    }
                }


            }
        });
        zZoomImageView.setOnScrollListener(new OnScrollListener() {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                Log.w(TAG,"@@wp onScroll: distanceX:" + distanceX + " distanceY:" + distanceY);

                return false;
            }
        });
        zZoomImageView.setOnDragListener(new OnDragListener() {
            @Override
            public void onDrag(MotionEvent ev,float dx, float dy) {

                if(!isReverse){
                    if(ev.getPointerCount() >1 ){return;}
                    Log.w(TAG,"@@wp onDrag: distanceX:" + dx + " distanceY:" + dy + "------" + gesture + ev.getPointerCount());
                    switch (gesture){
                        case 1:
                            ScaleEntity scaleEntity = new ScaleEntity();
                            scaleEntity.setAx(initxx );
                            initxx = initxx ;
                            scaleEntity.setAy(inityy + dy);
                            inityy = inityy + dy;
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 10;
                            msg.obj = scaleEntity;
                            handler.sendMessage(msg);
                            break;
                        case 2:
                            ScaleEntity scaleEntity1 = new ScaleEntity();
                            scaleEntity1.setAx(initxx );
                            initxx = initxx ;
                            scaleEntity1.setAy(inityy);
                            inityy = inityy ;
                            Message msg1 = handler.obtainMessage();
                            msg1.arg1 = 10;
                            msg1.obj = scaleEntity1;
                            handler.sendMessage(msg1);
                            break;
                        case 3:
                            ScaleEntity scaleEntity2 = new ScaleEntity();
                            scaleEntity2.setAx(initxx + dx);
                            initxx = initxx + dx;
                            scaleEntity2.setAy(inityy);
                            inityy = inityy ;
                            Message msg2 = handler.obtainMessage();
                            msg2.arg1 = 10;
                            msg2.obj = scaleEntity2;
                            handler.sendMessage(msg2);
                            break;
                        case 4:
                            ScaleEntity scaleEntity3 = new ScaleEntity();
                            scaleEntity3.setAx(initxx );
                            initxx = initxx ;
                            scaleEntity3.setAy(inityy);
                            inityy = inityy ;
                            Message msg3 = handler.obtainMessage();
                            msg3.arg1 = 10;
                            msg3.obj = scaleEntity3;
                            handler.sendMessage(msg3);
                            break;
                        case 5:
                            ScaleEntity scaleEntity4 = new ScaleEntity();
                            scaleEntity4.setAx(initxx );
                            initxx = initxx ;
                            scaleEntity4.setAy(inityy +dy);
                            inityy = inityy +dy;
                            Message msg4 = handler.obtainMessage();
                            msg4.arg1 = 10;
                            msg4.obj = scaleEntity4;
                            handler.sendMessage(msg4);
                            break;
                         case 6:
                             ScaleEntity scaleEntity5 = new ScaleEntity();
                             scaleEntity5.setAx(initxx );
                             initxx = initxx ;
                             scaleEntity5.setAy(inityy);
                             inityy = inityy ;
                             Message msg5 = handler.obtainMessage();
                             msg5.arg1 = 10;
                             msg5.obj = scaleEntity5;
                             handler.sendMessage(msg5);
                            break;
                        case 7:
                            ScaleEntity scaleEntity6 = new ScaleEntity();
                            scaleEntity6.setAx(initxx + dx);
                            initxx = initxx + dx;
                            scaleEntity6.setAy(inityy);
                            inityy = inityy ;
                            Message msg6 = handler.obtainMessage();
                            msg6.arg1 = 10;
                            msg6.obj = scaleEntity6;
                            handler.sendMessage(msg6);
                            break;
                        case 8:
                            ScaleEntity scaleEntity7 = new ScaleEntity();
                            scaleEntity7.setAx(initxx );
                            initxx = initxx ;
                            scaleEntity7.setAy(inityy);
                            inityy = inityy ;
                            Message msg7 = handler.obtainMessage();
                            msg7.arg1 = 10;
                            msg7.obj = scaleEntity7;
                            handler.sendMessage(msg7);
                            break;
                        case 9:
                            ScaleEntity scaleEntity8 = new ScaleEntity();
                            scaleEntity8.setAx(initxx + dx);
                            initxx = initxx + dx;
                            scaleEntity8.setAy(inityy + dy);
                            inityy = inityy +dy;
                            Message msg8 = handler.obtainMessage();
                            msg8.arg1 = 10;
                            msg8.obj = scaleEntity8;
                            handler.sendMessage(msg8);
                            break;
                    }
                }

            }
        });
        for(int i = 0; i < 10; i ++){

        }
    }
    /**
     * 获取wifi列表
     */
    private WifiManager wifiManager;
    private List<ScanResult> listb=null;
    private List<ScanResult> getWifiList(){
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
        listb = wifiManager.getScanResults();
        if(listb != null) {
            WifiInfo wi = wifiManager.getConnectionInfo();
            Log.w(TAG, "listb:" + listb.toString() + "'''" + wi.getBSSID());
        }
        return listb;
    }
    private void initPopwindow(View testGet, boolean flag){
        customPopwindow = new CustomPopwindow(this,R.layout.popwindow_startend_point,R.mipmap.popwindow_bg_bottom);
        customPopwindow.setWidth(200);
        customPopwindow.setHeight(80);
        if(flag){
            View contentView = customPopwindow.getContentView();
            contentView.measure(makeDropDownMeasureSpec(customPopwindow.getWidth()), makeDropDownMeasureSpec(customPopwindow.getHeight()));

            int offsetX = Math.abs(customPopwindow.getContentView().getMeasuredWidth()-testGet.getWidth()) /12;
            int offsetY = -testGet.getWidth();
            PopupWindowCompat.showAsDropDown(customPopwindow, testGet, offsetX, offsetY, Gravity.START);
        }else{

        }


        customPopwindow.setTvOnclickListener(new OnTvClickListener() {
            @Override
            public void tvClickListener(View v) {
                switch (v.getId()){
                    case R.id.tvStart:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TestActivity.this,"起点",Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;
                    case R.id.tvEnd:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TestActivity.this,"终点",Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;
                }
            }
        });
    }
    private int getItemHeight(ListView listview){
        ListAdapter listAdapter = listview.getAdapter();
        if (listAdapter == null) {
            return 0;
        }
        View listItem = listAdapter.getView(0, null, listview);
        listItem.measure(0, 0);
        return listItem.getMeasuredHeight();
    }
    private CustomPopwindow customPopwindow1;
    private void initPopwindow(PopupWindow popupWindow, boolean flag,int i){
        customPopwindow1 = new CustomPopwindow(this,R.layout.popwindow_startend_point,R.mipmap.popwindow_bg_right);
        customPopwindow1.setWidth(200);
        customPopwindow1.setHeight(80);
        if(flag){

        }else{
            View contentView = customPopwindow1.getContentView();
            contentView.measure(makeDropDownMeasureSpec(customPopwindow1.getWidth()), makeDropDownMeasureSpec(customPopwindow1.getHeight()));
            Log.w(TAG ,"@@@@@@@:" + getItemHeight(listview));
            int offsetX = -Math.abs(customPopwindow1.getContentView().getMeasuredWidth()+popupWindow.getWidth() + btSelectPerson.getWidth() /2 ) ;
            int offsetY = -popupWindow.getHeight()  + getItemHeight(listview) * i;
            PopupWindowCompat.showAsDropDown(customPopwindow1, btSelectPerson, offsetX, offsetY, Gravity.START);
        }


        customPopwindow1.setTvOnclickListener(new OnTvClickListener() {
            @Override
            public void tvClickListener(View v) {
                switch (v.getId()){
                    case R.id.tvStart:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TestActivity.this,"起点",Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;
                    case R.id.tvEnd:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TestActivity.this,"终点",Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;
                }
            }
        });
    }

    /**
     * select person
     */
    private ArrayList<PersonEntity> list;
    private ListView listview;
    private PersonAdapter personAdapter;
    private void initSelectPersonPopwindow(View v){
        initListViewPopwindow(v);
        list = new ArrayList<>();
        PersonEntity pe1 = new PersonEntity();
        pe1.setName("1");
        pe1.setState(0);
        PersonEntity pe2 = new PersonEntity();
        pe2.setName("2");
        pe2.setState(0);
        PersonEntity pe3 = new PersonEntity();
        pe3.setName("3");
        pe3.setState(0);
        PersonEntity pe4 = new PersonEntity();
        pe4.setName("4");
        pe4.setState(0);
        PersonEntity pe5 = new PersonEntity();
        pe5.setName("5");
        pe5.setState(0);
        PersonEntity pe6 = new PersonEntity();
        pe6.setName("6");
        pe6.setState(0);

        list.add(pe1);
        list.add(pe2);
        list.add(pe3);
        list.add(pe4);
        list.add(pe5);
        list.add(pe6);

        personAdapter = new PersonAdapter(this,list,R.layout.listview_item);
        listview.setAdapter(personAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                initPopwindow(customListviewPopwindow,false,position);
                runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TestActivity.this,"位置:" + position,Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });


    }
    private void showListviewPopwindow(CustomListviewPopwindow customListviewPopwindow,View v){
        View contentView = customListviewPopwindow.getContentView();
        contentView.measure(makeDropDownMeasureSpec(customListviewPopwindow.getWidth()), makeDropDownMeasureSpec(customListviewPopwindow.getHeight()));

        int offsetX = -customListviewPopwindow.getContentView().getMeasuredWidth();
        int offsetY = -(customListviewPopwindow.getContentView().getMeasuredWidth() +testGet.getWidth())/2;
        PopupWindowCompat.showAsDropDown(customListviewPopwindow, v, offsetX, offsetY, Gravity.START);
    }

    private CustomListviewPopwindow customListviewPopwindow;//select person
    private void initListViewPopwindow(View v){
        if(customListviewPopwindow != null && customListviewPopwindow.isShowing()){customListviewPopwindow.dismiss();}
        customListviewPopwindow = new CustomListviewPopwindow(this,R.layout.listview_person);
        customListviewPopwindow.setWidth(140);
        customListviewPopwindow.setHeight(200);

        listview = customListviewPopwindow.getListview();
//        customListviewPopwindow.setTvOnclickListener(new OnTvClickListener() {
//            @Override
//            public void tvClickListener(View v) {
//                switch (v.getId()){
//                    case R.id.tvStart:
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(TestActivity.this,"起点",Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                        break;
//                    case R.id.tvEnd:
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(TestActivity.this,"终点",Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                        break;
//
//                }
//            }
//        });
    }
    @SuppressWarnings("ResourceType")
    private static int makeDropDownMeasureSpec(int measureSpec) {
        int mode;
        if (measureSpec == ViewGroup.LayoutParams.WRAP_CONTENT) {
            mode = View.MeasureSpec.UNSPECIFIED;
        } else {
            mode = View.MeasureSpec.EXACTLY;
        }
        return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), mode);
    }

    private Handler handler= new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 10:
                    ScaleEntity scaleEntity = (ScaleEntity) msg.obj;
    //              LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(100, 80);
    //                lp.setMargins(new Double(msg.).intValue() ,
    //                        new Double(focusY + Math.abs(inity - focusY)*scaleFactor).intValue(),
    //                        screenWidth - new Double(focusX + Math.abs(initx - focusX) * scaleFactor).intValue() ,
    //                        new Double( mce.getyPix()/2 + 1.0/0.05 * (mce.getyPix() /384) + 40).intValue());
    //
    //
    //                fl.updateViewLayout(textViews.get(0),lp);
    //                fl.invalidate();
                    translate(scaleEntity.getAx(),scaleEntity.getAy());
                    break;
            }
        }
    };
    private void initData() {




//        imageViewScaleChangeListenerIml = new ImageViewScaleChangeListenerIml();
        mce = CommonUtils.getMapCenter1(zZoomImageView);
        Log.i(TAG,"@@WP:" + mce.getxPix() + "--" + mce.getyPix() + screenWidth /2);
    }

    private void addView() {
        if(dots == null) {
            dots = new ArrayList<>();
        }
        TaskDots td1 = new TaskDots();
        td1.setId("1");
        td1.setName("1");
        td1.setX(1.0f);
        td1.setY(1.0f);

        TaskDots td2 = new TaskDots();
        td2.setId("2");
        td2.setName("2");

        td2.setX(3.0f);
        td2.setY(1.0f);


        TaskDots td3 = new TaskDots();
        td3.setId("3");
        td3.setName("3");
        td3.setX(4);
        td3.setY(3);

        TaskDots td4 = new TaskDots();
        td4.setId("4");
        td4.setName("4");
        td4.setX(1);
        td4.setY(3);
        dots.add(td1);
        dots.add(td2);
        dots.add(td3);
        dots.add(td4);
        int i = 0;
        textViews = new ArrayList<>();
        for (final TaskDots td : dots){
            TextView tvIcon1 = new TextView(this);
            tvIcon1.setTextColor(this.getResources().getColor(R.color.blue));
            tvIcon1.setHeight(10);
            tvIcon1.setWidth(1000);
            tvIcon1.setLongClickable(true);
            tvIcon1.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    //弹出dialog
                    alertDialog(td.getName());
                    return false;
                }
            });
            tvIcon1.setText(td1.getName()+"00");
            tvIcon1.setBackground(this.getResources().getDrawable(R.drawable.weizhi_2));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(100, 80);
            lp.setMargins(screenWidth/2 + new Double(td.getX() /0.05 * (screenWidth /384)).intValue() - 50 ,
                    new Double(mce.getyPix()/2).intValue() - new Double(td.getY()/0.05 * (mce.getyPix() /384)).intValue() - 40,
                    screenWidth/2 - new Double(td.getX()/0.05 * screenWidth /384).intValue() + 50 ,
                    new Double( mce.getyPix()/2 + td.getY()/0.05 * (mce.getyPix() /384) + 40).intValue());

            textViews.add(tvIcon1);
            fl.addView(tvIcon1, lp);

        }

    }
private float geticonx = screenWidth/2 + new Double(1.0 /0.05 * (screenWidth /384)).intValue() - 50;
    private float geticony = screenWidth/2 + new Double(1.0 /0.05 * (screenWidth /384)).intValue() - 40;
    private void alertDialog(String name){
        new AlertDialog.Builder(this)
                .setTitle("任务的起点")
                .setIcon(android.R.drawable.ic_dialog_info)
//                .setView(edt)
                .setMessage(name )
                .setCancelable(true)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
//                        Toast.makeText(RegisterActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
//                    if(isClick){
//
//                    }else{
//
//                    }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }
//    @Override public boolean onTouchEvent(MotionEvent me) {
//        if (detector != null) return detector.onTouchEvent(me);
//        else return scDetector.onTouchEvent(me);
//    }
//
//    @Override
//    public boolean onDown(MotionEvent e) {
//        Toast.makeText(TestActivity.this, "onDown", Toast.LENGTH_SHORT).show();
//
//        return true;
//    }
//
//    @Override
//    public void onShowPress(MotionEvent e) {
//        Toast.makeText(TestActivity.this, "onShowPress", Toast.LENGTH_SHORT).show();
//    }
//
//    @Override
//    public boolean onSingleTapUp(MotionEvent e) {
//        Toast.makeText(TestActivity.this, "onSingleTapUp", Toast.LENGTH_SHORT).show();
//        return true;
//    }
//
//    //-----------------------implement OnScaleGestureListener's method----------------------//
//
//
//    @Override
//    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
//        Toast.makeText(TestActivity.this, "onScroll", Toast.LENGTH_SHORT).show();
//        return true;
//    }
//
//    @Override
//    public void onLongPress(MotionEvent e) {
//        Toast.makeText(TestActivity.this, "onLongPress", Toast.LENGTH_SHORT).show();
//
//    }
//
//    @Override
//    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//        Toast.makeText(TestActivity.this, "onFling", Toast.LENGTH_SHORT).show();
//        return true;
//    }
//
//    @Override
//    public boolean onScale(ScaleGestureDetector detector) {
//        Toast.makeText(TestActivity.this, "onScale", Toast.LENGTH_SHORT).show();
//        return true;
//    }
//
//    @Override
//    public boolean onScaleBegin(ScaleGestureDetector detector) {
//        Toast.makeText(TestActivity.this, "onScaleBegin", Toast.LENGTH_SHORT).show();
//        return true;
//    }
//
//    @Override
//    public void onScaleEnd(ScaleGestureDetector detector) {
//        Toast.makeText(TestActivity.this, "onScaleEnd", Toast.LENGTH_SHORT).show();
//    }
//
    int ii = 0;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_test_ges:
//                detector = new GestureDetector(this, this);
//                scDetector = null;


//                initPopwindow(v,true);

//                getWifiListAndVoice();




//                ArrayList<ScanResult> list = (ArrayList<ScanResult>)getWifiList();
//                if(list != null){
////                    wifis.setText("-----" +  audioRecordDemo.getNoise());
////                    wifis.setText(audioRecordDemo.getNoise() + "-----" +  list.toString());
//
//                }else{
//                    wifis.setText(null);
//                }
//                Wifilists wifilists = new Wifilists();
//                ArrayList<WifiEnty> arrayList = new ArrayList<>();
//                WifiEnty wifiEnty  =null;
//                for (ScanResult sr : list){
////                                        hashMap.put(i + "",sr.SSID+":" + sr.level);
//                    wifiEnty = new WifiEnty();
//                    Log.w(TAG,"sr.SSID:" + sr.SSID );
////                    sb.append("!").append(sr.SSID).append("$").append(sr.level);
//
//                    wifiEnty.setWifiname(sr.SSID);
//                    wifiEnty.setLevel(sr.level + "");
//                    wifiEnty.setNoise(audioRecordDemo.getNoise() + "");
////                    wifiEnty.setIndex(i);
//                    arrayList.add(wifiEnty);
//
//                }
//                wifilists.setIndex(i);
//                wifilists.setWifiEntyArrayList(arrayList);
//                saveData(new Gson().toJson(wifilists));
//                wifis.setText(new Gson().toJson(wifilists));
////                saveData("\n\t"+i+"\n\t");
//                ++ii;
                break;
            case R.id.bt_test_scges:
//                scDetector = new ScaleGestureDetector(this, this);
//                detector = null;
                initPopwindow(v,true);
                break;
            case R.id.btSelectPerson:
//                initListViewPopwindow(btSelectPerson);
                showListviewPopwindow(customListviewPopwindow, btSelectPerson);
                break;
        }
    }

    private void getWifiListAndVoice() {




    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if(audioStream != null)audioStream.stop();
//        if(mediaRecordDemo != null)mediaRecordDemo.stopRecord();
        if(audioRecordDemo != null)audioRecordDemo.setGetVoiceRun(false);
    }

    private void translate(float x, float y) {
        TranslateAnimation translateAnimation = new TranslateAnimation((initxx), (x), (inityy), (y));
        translateAnimation.setDuration(50);
        translateAnimation.setFillAfter(true);
        ivLocation.setAnimation(translateAnimation);
        ivLocation.startAnimation(translateAnimation);

        Log.w(TAG,"preLocation: (" + initxx + ", " + inityy + "),  afterLocation: (" + x + ", " + y + ")");

        initxx = x;
        inityy = y;
        translateAnimation = null;
    }
}
